package me.shingohu.man.mvp;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by hujie on 17/4/15.
 */

public class BasePresenter<M extends IModel, V extends IView> implements IPresenter {

    private CompositeDisposable mCompositeDisposable;
    protected M mModel;
    private WeakReference<V> mWeakReference;


    public BasePresenter(M model, V rootView) {
        this.mModel = model;
        mWeakReference = new WeakReference<>(rootView);
        onCreate();
    }

    public BasePresenter(V rootView) {
        mWeakReference = new WeakReference<>(rootView);

        onCreate();
    }

    public BasePresenter() {
        onCreate();
    }


    /**
     * 是否使用eventBus,默认为使用(false)，
     *
     * @return
     */
    protected boolean useEventBus() {
        return false;
    }

    protected void register() {
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
    }

    protected void unRegister() {
        if (useEventBus()) {
            EventBus.getDefault().unregister(this);
        }
    }


    @Override
    public void onCreate() {
        register();
    }

    @Override
    public void onDestroy() {
        unRegister();
        unDisposable();
        onDestoryView();
        mModel.onDestroy();
        mCompositeDisposable = null;
        mModel = null;
    }

    private void onDestoryView() {
        if (mWeakReference != null) {
            mWeakReference.clear();
            mWeakReference = null;
        }
    }

    public V getView() {
        if (mWeakReference != null) {
            return mWeakReference.get();
        }
        return null;
    }

    protected void addDisposable(Disposable disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);//disposable,集中处理
    }

    protected void unDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();//保证activity结束时取消所有正在执行的订阅
        }
    }

}
